# core/router.py
import inspect
from typing import List, Dict, Any

from fastapi import FastAPI,Request
async def apply_middlewares(request: Request, handler, middlewares: list):
    """按顺序执行中间件，返回第一个非None响应或执行原始处理函数"""
    for middleware in middlewares:
        # 执行中间件（异步）
        response = await middleware(request)
        if response is not None:  # 中间件返回响应，终止执行
            return response
    # 所有中间件执行完毕，执行原始处理函数
    return await handler(request)

def register_routes(app: FastAPI, plugins: List[Dict[str, Any]]):
    """注册所有插件路由"""
    for plugin in plugins:
        # 遍历每个方法，注册路由
        for method in plugin["methods"]:
            path = method["path"].lower()  # 如 /plugins/demo_plugin/user/order/CreateOrder/get
            http_method = method["method"].lower()  # 如 get/post
            handler = method["handler"]  # 控制器方法

            print(f"注册路由：{http_method.upper()} {path}")
            # 定义路由处理函数（自动注入request）
            # print(f"""
            # 注册路由：
            #   路径: {path}
            #   方法: {http_method.upper()}
            #   处理函数: {handler.__name__}
            #   参数类型: {[p.annotation.__name__ for p in inspect.signature(handler).parameters.values() if p.annotation != inspect.Parameter.empty]}
            # """)
            # 注册路由到FastAPI
            # async def wrapped_handler(request: Request):
            #     # 执行中间件并返回响应（若有）
            #     return await apply_middlewares(request, handler, middlewares)
            app.add_api_route(path=path, endpoint=handler, methods=[http_method])
            # if middlewares and len(middlewares):
            #     app.add_api_route(path=path, endpoint=handler, methods=[http_method])
            # else:
            #     app.add_api_route(path=path, endpoint=handler, methods=[http_method])